import React, {RefObject} from 'react'
import styles from './manage.module.css'
import {InputItem, TextareaItem, Switch, Picker, Toast} from 'antd-mobile'
import cityData from './cityData'
import Btn from '../../../components/btn'
import Nav from '../../../components/nav'
import {createForm} from 'rc-form'
import request from "../../../utils/request";
import {withRouter, RouteComponentProps} from 'react-router-dom'

const CustomChildren: any = React.forwardRef((props: any, ref: any) => {
    return (
        <div
            onClick={props.onClick}
            style={{backgroundColor: '#fff', paddingLeft: 15}}
        >
            <div style={{display: 'flex', height: '45px', lineHeight: '45px'}}>
                <div style={{
                    flex: 1,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                }}>{props.children}</div>
                <div style={{textAlign: 'right', color: '#888', marginRight: 15}} ref={ref}>{props.extra}</div>
            </div>
        </div>
    );
});


interface Props extends RouteComponentProps<{ addrId: string }> {
    form: any
}

interface States {
    username: string,
    userPhone: string,
    areaCodes: any[],
    addressDetail: string,
    isDefault: boolean
}

class Index extends React.Component<Props> {

    state: States = {
        username: '',
        userPhone: '',
        areaCodes: [],
        addressDetail: '',
        isDefault: false
    };

    componentDidMount() {
        const {match: {params}} = this.props;
        const addrId = parseInt(params.addrId);
        if (addrId > 0) {
            request(`/addresses/detail?addrId=${addrId}`).then((result) => {
                const {addressDetail} = result.data;
                console.log(addressDetail);
                this.setState(addressDetail)
            }).catch(() => {
                Toast.fail('请求失败')
            });
        }
    }

    protected areaTextRef: RefObject<any>;

    constructor(props: any) {
        super(props);
        this.areaTextRef = React.createRef();
    }

    addressSave = () => {
        const {form: {validateFields}, history, match: {params: {addrId}}} = this.props;
        validateFields((error: any, values: any) => {
            values.areaText = this.areaTextRef.current.innerText;
            console.log("validateFields");
            console.log(values);
            values.addressFull = values.areaText + values.addressDetail;
            values.areaCodes = JSON.stringify(values.areaCodes);
            if (error) {
                return Toast.fail('表单验证失败');
            }
            request(`/address/${addrId}`, {
                method: 'POST',
                data: values
            }).then((result) => {
                Toast.success('操作成功', 1, () => {
                    history.goBack();
                });
            }).catch(() => {
                Toast.fail('请求失败');
            });
        });
    };


    addressDelete = () => {
        const {history} = this.props;
        history.goBack();
    };

    // onChangeAddress = (value) => {
    //     console.log("value");
    //     console.log(value);
    //     this.setState({
    //         selectedVal: value
    //     });
    // };

    render() {
        const {form: {getFieldProps}, match: {params}} = this.props;
        const addrId = parseInt(params.addrId);
        return (
            <div className={styles.container}>
                <Nav/>
                <div className={styles.contact}>
                    <InputItem
                        placeholder={"请输入联系人名称"}
                        {...getFieldProps('username', {
                            rules: [{required: true}],
                            initialValue: this.state.username
                        })}
                    />
                    <InputItem
                        placeholder={"请输入联系电话"}
                        {...getFieldProps('userPhone', {
                            rules: [{required: true}],
                            initialValue: this.state.userPhone
                        })}
                    />
                </div>

                <div className={styles.addr}>
                    <Picker
                        data={cityData}
                        title="区域"
                        // onChange={this.onChangeAddress}
                        // value={this.state.selectedVal}
                        {...getFieldProps('areaCodes', {
                            initialValue: this.state.areaCodes,
                        })}
                    >
                        <CustomChildren ref={this.areaTextRef}>选择地址</CustomChildren>
                    </Picker>
                    <TextareaItem
                        rows={4}
                        placeholder={"请输入详细地址：如街道、门牌号、小区、楼幢号、单元室"}
                        {...getFieldProps('addressDetail', {
                            initialValue: this.state.addressDetail,
                        })}
                    />
                </div>

                <div className={styles.defaultAddr}>
                    <b>设为默认地址</b>
                    <Switch
                        checked={true}
                        {...getFieldProps('isDefault', {
                            initialValue: this.state.isDefault,
                            valuePropName: 'checked',
                        })}
                    />
                </div>

                <div className={styles.btn}>
                    <Btn style={{
                        width: '98%',
                        margin: '20px auto 5px'
                    }} val={"确认"} onClick={() => {
                        this.addressSave()
                    }}/>
                    {addrId > 0 && <Btn style={{
                        width: '98%',
                        backgroundColor: 'white',
                        boxShadow: '0 0 16px 0 rgba(0, 0, 0, 0.1)',
                        color: 'black'
                    }} val={"删除地址"} onClick={this.addressDelete}/>}

                </div>
            </div>
        );
    }
}

export default createForm()(withRouter(Index))
